﻿Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Web.UI
Imports System.Web.UI.WebControls



Public Class _Default
    Inherits System.Web.UI.Page

    ' methodos fortwsis
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        bindData()

    End Sub
    ' antikeimeno xeirismou twn dedomenwn
    Public Model As DefaultViewModels

    Private Function getSearchTerm() As String
        Return If(Request.QueryString("searchTerm"), "")
    End Function
    Private Function getSearchField() As String
        Return If(Request.QueryString("searchField"), "")
    End Function
    Private Function getSearchType() As String
        Return If(Request.QueryString("type"), "")
    End Function
    Private Function getLimit() As String
        Return If(Request.QueryString("limit"), "")
    End Function
    ' methodos pou kanei probolh twn dedomenwn sta listview
    Private Sub bindData()
        Model = getDefaultViewModel(getSearchTerm(), getSearchField(), getSearchType())

        Dim limit = If(getLimit() = "", 3, Convert.ToInt32(getLimit()))
        If limit > 0 Then
            'litDatabaseRecordsCount.Text = "<div class=""margin_top10"">And <b>" + (Model.AllSampleData.Count() - limit) + "</b> more records... " + "(<a href=""" + Request.ApplicationPath + "?limit=0"">See All</a>)</div>"
            DatabaseListView.DataSource = Model.AllSampleData.Take(limit)
        Else
            DatabaseListView.DataSource = Model.AllSampleData
        End If
        DatabaseListView.DataBind()

        Dim searchIndex = Model.AllSearchIndexData
        If getSearchTerm() <> String.Empty Then
            searchIndex = Model.SampleSearchResults
        End If

        searchListView.DataSource = searchIndex
        searchListView.DataBind()

        ComboBox.DataValueField = "Value"
        ComboBox.DataTextField = "Text"
        ComboBox.DataSource = Model.SearchFieldList
        ComboBox.DataBind()

        searchBox.Text = getSearchTerm()
        ComboBox.SelectedValue = getSearchField()
        CheckBox.Checked = getSearchType() = "default"
    End Sub

    Private Function getDefaultViewModel(ByVal searchTerm As String, ByVal searchField As String, Optional ByVal type As String = "") As DefaultViewModels
        ' dimiourgia default euretiriou anazitisis tis Lucene 
        If Not IO.Directory.Exists(GoLucene._luceneDir) Then
            IO.Directory.CreateDirectory(GoLucene._luceneDir)
        End If

        ' pragmatopoihsh tis anazitisis
        Dim searchResults As IEnumerable(Of SampleData) = New List(Of SampleData)()
        If String.IsNullOrEmpty(type) Then
            searchResults = If(String.IsNullOrEmpty(searchField), GoLucene.Search(searchTerm), GoLucene.Search(searchTerm, searchField))
        ElseIf type = "default" Then
            searchResults = If(String.IsNullOrEmpty(searchField), GoLucene.SearchDefault(searchTerm), GoLucene.SearchDefault(searchTerm, searchField))
        End If

        ' dimiourgia kai epistrofh tis dimioyrgiaw dedomenwn
        Dim search_field_list = New List(Of SelectedList)() From { _
         New SelectedList() With { _
          .Text = "(All Fields)", _
          .Value = "" _
         }, _
         New SelectedList() With { _
          .Text = "Κωδικός_Ταινίας", _
          .Value = "Id" _
         }, _
         New SelectedList() With { _
          .Text = "Όνομα_Ταινίας", _
          .Value = "movieName" _
         }, _
         New SelectedList() With { _
          .Text = "Έτος Προβολής", _
          .Value = "Year" _
         }, _
        New SelectedList() With { _
          .Text = "Σκηνοθέτης", _
          .Value = "directory" _
         }, _
        New SelectedList() With { _
          .Text = "Κατηγορία", _
          .Value = "category" _
         }, _
        New SelectedList() With { _
          .Text = "Αστέρια", _
          .Value = "movieStars" _
         } _
       }
        Return New DefaultViewModels() With { _
         .AllSampleData = SampleDataRepository.GetAll(), _
         .AllSearchIndexData = GoLucene.GetAllIndexRecords(), _
         .SampleData = New SampleData() With { _
          .movieID = 11, _
          .movieName = "Harry Potter and the Deathly Hallows Part2", _
          .Year = 2009, _
          .directory = "Chris Columbus", _
          .category = "2011", _
          .movieStars = 8 _
         }, _
         .SampleSearchResults = searchResults, _
         .SearchFieldList = search_field_list _
        }
    End Function
    'mhnuma epityxoys dimiourgia euretiriou
    Private Sub createIndex()
        GoLucene.AddUpdateLuceneIndex(SampleDataRepository.GetAll())
        Label8.Text = "Search index was created successfully!"
        bindData()
    End Sub
    'prosthiki egrafis sto euretirio
    Private Sub addToIndex(ByVal sampleData As SampleData)
        GoLucene.AddUpdateLuceneIndex(sampleData)
        Label8.Text = "Record was added to search index successfully!"
        bindData()
    End Sub
    ' katharismos euretiriou
    Private Sub clearIndex()
        If GoLucene.ClearLuceneIndex() Then
            Label8.Text = "Search index was cleared successfully!"
        Else
            Label8.Text = "Index is locked and cannot be cleared, try again later or clear manually!"
        End If
        bindData()
    End Sub
    ' katharismos egrafwn euretiriou
    Private Sub clearIndexRecord(ByVal id As Integer)
        GoLucene.ClearLuceneIndexRecord(id)
        Label8.Text = "Search index record was deleted successfully!"
        bindData()
    End Sub

    Private Sub optimizeIndex()
        GoLucene.Optimize()
        Label8.Text = "Search index was optimized successfully!"
        bindData()
    End Sub
    'diagrafei egrafwn
    Protected Sub lvSearchIndex_OnItemDeleting(ByVal sender As Object, ByVal e As ListViewDeleteEventArgs)
        Dim recordId = CInt(DatabaseListView.DataKeys(e.ItemIndex).Value)
        clearIndexRecord(recordId)
    End Sub

    ' koumpi dimiourgias euretiriou
    Protected Sub CreateIndex_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonIndex.Click
        createIndex()
    End Sub
    Protected Sub buttonOptimize_Click(ByVal sender As Object, ByVal e As EventArgs)
        optimizeIndex()
    End Sub
    'katharismow euretiriou
    Protected Sub buttonIndex_Click(ByVal sender As Object, ByVal e As EventArgs)
        clearIndex()
    End Sub
    'koumpi sprothikis egrafis se euretirio
    Protected Sub SaveButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles saveButton.Click
        Dim id As Integer
        If Not Integer.TryParse(textID.Text, id) Then
            Label8.Text = "'Id' must be a number!"
            Return
        End If
        addToIndex(New SampleData() With { _
         .movieID = textID.Text, _
         .movieName = textName.Text, _
         .Year = textYear.Text, _
         .directory = textDirectory.Text, _
         .category = textCategory.Text, _
         .movieStars = textStars.Text _
        })
    End Sub
    'koumpi anazitisis
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonSearch.Click
        Response.Redirect(Request.ApplicationPath + "?searchTerm=" + searchBox.Text + "&searchField=" + ComboBox.SelectedValue + "&type=" + (If(CheckBox.Checked, "default", "")))
    End Sub

   
End Class